import * as fs from 'node:fs'
import * as path from 'node:path'
import { fileURLToPath } from 'node:url'
import iconv from 'iconv-lite'
import { getMessageQueueConfig } from './config'

// 串口消息队列
export class MessageQueue {
  private readonly config = getMessageQueueConfig()
  data: string // Declare the data property

  constructor() {
    this.data = ''
  }

  add(message: string): void {
    if (this.data.length >= this.config.maxLength) {
      this.data = this.data.substring(this.config.cleanupThreshold) // Update to assign the result
    }
    this.data += message
  }

  getData(): string {
    return this.data
  }

  reset(): void {
    this.data = ''
  }
}

// 生成屏幕指令, unicode 转 gb2312 转 16 进制
export function generateScreenCommandBody(str: string): string {
  const encodedBytes = iconv.encode(str, 'gb2312')
  // 转十六进制字符串
  const hexString = Array.from(encodedBytes)
    .map(byte => byte.toString(16).toUpperCase().padStart(2, '0'))
    .join('')
  return hexString
}

// 获取项目根目录
export function getProjectRoot(): string {
  // 在 ES module 中获取当前文件的目录
  const currentFileUrl = import.meta.url
  const currentFilePath = fileURLToPath(currentFileUrl)
  const currentDir = path.dirname(currentFilePath)

  // 从当前文件目录向上查找项目根目录（包含 package.json 的目录）
  let projectRoot = currentDir
  while (projectRoot !== path.dirname(projectRoot)) {
    if (fs.existsSync(path.join(projectRoot, 'package.json'))) {
      break
    }
    projectRoot = path.dirname(projectRoot)
  }

  return projectRoot
}
